<template>
  <div class="app-container">
    <PageSearch :showSearch.sync="showSearch" :getList="getList" :handleQuery="handleQuery" :resetQuery="resetQuery">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <template #form>
        <el-form :model="queryParams" ref="queryForm" size="small">
          <el-row>
            <el-form-item prop="cesNo">
              <el-input
                :placeholder="$t('耗材编号')"
                v-model="queryParams.cesNo"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item prop="cesName">
              <el-input
                :placeholder="$t('耗材名称')"
                v-model="queryParams.cesName"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item prop="cesType">
              <el-select
                @change="handleQuery"
                clearable
                :placeholder="$t('耗材类型')"
                style="width: 100%"
                v-model="queryParams.cesType"
              >
                <el-option label="商品包装耗材" :value="1" />
                <el-option label="订单发货耗材" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item prop="num">
              <el-input-number
                style="width: 240px"
                v-model="queryParams.num"
                :placeholder="$t('库存数量少于')"
                controls-position="right"
              />
            </el-form-item>
          </el-row>
        </el-form>
      </template>
      <template #actions>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['distribution:skuConsumable:add']"
        >
          {{ $t('新增') }}
        </el-button>

        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['distribution:skuConsumable:edit']"
        >
          {{ $t('修改') }}
        </el-button>

        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['distribution:skuConsumable:remove']"
        >
          {{ $t('删除') }}
        </el-button>

        <!-- <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['distribution:skuConsumable:export']">
          {{ $t('导出') }}
        </el-button> -->
      </template>
    </PageSearch>

    <el-table
      :height="calTableHeight()"
      v-loading="loading"
      ref="TableRef"
      :data="skuConsumableList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column show-overflow-tooltip type="selection" width="55" align="center" />
      <el-table-column show-overflow-tooltip label="耗材编号" align="center" prop="cesNo" width="180">
        <template slot-scope="{ row }">
          <div
            v-if="$hasPermission('distribution:skuConsumablePurchase:edit')"
            style="color: #0079d7"
            @click="handleUpdate(row)"
          >
            {{ row.cesNo }}
          </div>
          <div v-else style="color: #0079d7">{{ row.cesNo }}</div>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="耗材名称" align="center" prop="cesName" width="180" />
      <el-table-column label="耗材图片" align="center" prop="cesImg">
        <template slot-scope="{ row }">
          <el-image
            style="width: 50px; height: 50px"
            fit="contain"
            :key="Math.random()"
            v-hover="row.cesImg"
            :src="row.cesImg + '?x-oss-process=image/resize,w_100/quality,q_70'"
          />
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="耗材规格型号" align="center" prop="specification" width="150" />

      <el-table-column show-overflow-tooltip label="耗材库位号" align="center" prop="cesPositionNo" />
      <!-- 耗材类型 1-商品耗材 2-订单捆包耗材 -->
      <el-table-column show-overflow-tooltip label="耗材类型" align="center" prop="cesType">
        <template slot-scope="{ row }">
          <span v-if="row.cesType == 1">商品耗材</span>
          <span v-if="row.cesType == 2">订单捆包耗材</span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="数量" align="center" prop="num">
        <template slot-scope="{ row }">
          <div
            :style="{
              color: row.num < 0 ? 'red' : '',
            }"
          >
            {{ row.num }}
          </div>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="价格" align="center" prop="price" />
      <!-- 价格单位 1-RMB 2-JPY 3-USD -->
      <el-table-column show-overflow-tooltip label="价格单位" align="center" prop="priceUnit">
        <template slot-scope="{ row }">
          <span v-if="row.priceUnit == 1">RMB</span>
          <span v-if="row.priceUnit == 2">JPY</span>
          <span v-if="row.priceUnit == 3">USD</span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="采购备注" width="100" align="center" prop="purchaseRemark" />
      <el-table-column show-overflow-tooltip :label="$t('备注')" width="100" align="center" prop="remark" />
      <el-table-column show-overflow-tooltip :label="$t('操作')" align="center" fixed="right" :width="100">
        <template #default="{ row }">
          <el-dropdown @command="(command) => handleCommand(command, row)">
            <span class="el-dropdown-link">
              {{ $t('更多') }}
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-hasPermi="['distribution:skuConsumablePurchase:add']" command="handlePurchase">
                {{ $t('采购') }}
              </el-dropdown-item>
              <!-- <el-dropdown-item v-hasPermi="['distribution:skuConsumablePurchase:edit']" command="handleUpdate">
                {{ $t('修改') }}
              </el-dropdown-item> -->
              <el-dropdown-item v-hasPermi="['distribution:skuConsumablePurchase:add']" command="handleDelete">
                {{ $t('删除') }}
              </el-dropdown-item>
              <el-dropdown-item
                v-hasPermi="['distribution:skuConsumablePurchase:getSkuConsumableRecordList']"
                command="handleStockHis"
              >
                {{ $t('库存记录') }}
              </el-dropdown-item>

              <el-dropdown-item
                v-hasPermi="['distribution:skuConsumableRelevance:list']"
                command="handleSkuConsumableRelevance"
              >
                {{ $t('商品关联关系') }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品SKU耗材对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="耗材编号" prop="cesNo">
          <el-input v-model="form.cesNo" readonly placeholder="请输入耗材编号" />
        </el-form-item>
        <el-form-item label="耗材名称" prop="cesName">
          <el-input v-model="form.cesName" placeholder="请输入耗材名称" />
        </el-form-item>
        <el-form-item label="耗材规格型号" prop="specification">
          <el-input v-model="form.specification" placeholder="请输入耗材规格型号" />
        </el-form-item>
        <el-form-item label="耗材类型" prop="cesType">
          <el-select style="width: 100%" v-model="form.cesType">
            <el-option label="商品包装耗材" :value="1" />
            <el-option label="订单发货耗材" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="耗材图片" prop="cesImg">
          <ImgUploadManage :needSplit="false" type="9" :businessId="form.id" :fileList.sync="form.cesImg" />
        </el-form-item>
        <el-form-item label="耗材库位号" prop="cesPositionNo">
          <el-input v-model="form.cesPositionNo" placeholder="请输入耗材库位号" />
        </el-form-item>

        <el-form-item label="采购链接1" prop="purchaseLink1">
          <el-input v-model="form.purchaseLink1" placeholder="请输入采购链接1" />
        </el-form-item>
        <el-form-item label="采购链接2" prop="purchaseLink2">
          <el-input v-model="form.purchaseLink2" placeholder="请输入采购链接2" />
        </el-form-item>
        <el-form-item label="采购链接3" prop="purchaseLink3">
          <el-input v-model="form.purchaseLink3" placeholder="请输入采购链接3" />
        </el-form-item>
        <el-form-item label="采购备注" prop="purchaseRemark">
          <el-input v-model="form.purchaseRemark" placeholder="请输入采购备注" />
        </el-form-item>
        <el-form-item :label="$t('备注')" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 采购 -->
    <Purchase :show.sync="purchase.show" :formData="purchase.form" @success="getList" />
    <!-- 耗材使用情况 -->
    <ConsumableUsage :show.sync="consumableUsage.show" :formData="consumableUsage.formData" @success="getList" />
    <!-- 库存记录 -->
    <StockHis :show.sync="stockHis.show" :formData="stockHis.formData" @success="getList" />
    <!-- 商品关联关系 -->
    <SkuConsumableRelevance
      :show.sync="skuConsumableRelevance.show"
      :formData="skuConsumableRelevance.formData"
      @success="getList"
    />
  </div>
</template>

<script>
import {
  listSkuConsumable,
  getSkuConsumable,
  delSkuConsumable,
  addSkuConsumable,
  updateSkuConsumable,
} from '@/api/distribution/sku/skuConsumable'
import { getCesNo } from '@/api/distribution/sku/skuConsumablePurchase'
import Purchase from './components/purchase.vue'
import { getToken } from '@/utils/auth'
import ConsumableUsage from './components/consumableUsage.vue'
import StockHis from './components/stockHis.vue'
import SkuConsumableRelevance from './components/skuConsumableRelevance.vue'
import { checkPermi } from '@/utils/permission'

export default {
  activated() {
    this.$nextTick(() => this.$refs['TableRef']?.doLayout())
  },
  name: 'SkuConsumable',
  components: { SkuConsumableRelevance, Purchase, ConsumableUsage, StockHis },
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + '/system/oss/upload',
      headers: {
        Authorization: 'Bearer ' + getToken(),
      },
      /**
       * 商品关联关系
       */
      skuConsumableRelevance: {
        show: false,
        formData: {},
      },
      /**
       * 库存记录
       */
      stockHis: {
        show: false,
        formData: {},
      },
      /**
       * 耗材使用情况
       */
      consumableUsage: {
        show: false,
        formData: {},
      },
      /**
       * 采购
       */
      purchase: {
        show: false,
        form: {},
      },

      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 商品SKU耗材表格数据
      skuConsumableList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cesNo: undefined,
        cesName: undefined,
        specification: undefined,
        cesImg: undefined,
        cesPositionNo: undefined,
        cesType: undefined,
        num: undefined,
        price: undefined,
        priceUnit: undefined,
        purchaseLink1: undefined,
        purchaseLink2: undefined,
        purchaseLink3: undefined,
        purchaseRemark: undefined,
      },
      // 表单参数
      form: {
        /**耗材编号 */
        cesNo: '',
        num: '',
        priceTotal: '',
        priceUnit: '',
        cesTotalAmount: '',
        cesUnitPrice: '',
        purchaseRemark: '',
        refundNum: '',
        refundPrice: '',
        refundPriceUnit: '',
        refundReason: '',
        receiveNum: '',
        purchaseLink: '',
        remark: '',
      },
      // 表单校验
      rules: {
        id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
        cesNo: [{ required: true, message: '耗材编号不能为空', trigger: 'blur' }],
        cesName: [{ required: true, message: '耗材名称不能为空', trigger: 'blur' }],
        specification: [{ required: true, message: '耗材规格型号不能为空', trigger: 'blur' }],
        cesImg: [{ required: true, message: '耗材图片不能为空', trigger: 'blur' }],
        cesPositionNo: [{ required: true, message: '耗材库位号不能为空', trigger: 'blur' }],
        cesType: [
          {
            required: true,
            message: '耗材类型 1-商品耗材 2-订单捆包耗材不能为空',
            trigger: 'change',
          },
        ],
        num: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
        price: [{ required: true, message: '价格不能为空', trigger: 'blur' }],
        priceUnit: [
          {
            required: true,
            message: '价格单位 1-RMB 2-JPY 3-USD不能为空',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  computed: {},
  created() {
    this.getList()
  },
  methods: {
    handleCommand(command, row) {
      this[command](row)
    },
    handleSkuConsumableRelevance(row) {
      this.skuConsumableRelevance.formData = row
      this.skuConsumableRelevance.show = true
    },
    handleStockHis(row) {
      this.stockHis.formData = row
      this.stockHis.show = true
    },
    handleConsumableUsage(row) {
      const hasPermission = checkPermi(['distribution:skuConsumable:getConsumableRecordsByCesId'])
      if (!hasPermission) return
      this.consumableUsage.formData = row
      this.consumableUsage.show = true
    },
    handleUploadSuccess(e) {
      console.log(`e ==>`, e)
    },
    handlePurchase(row) {
      // console.log(` ==>`, JSON.parse(JSON.stringify(row)));
      this.purchase.show = true
      this.purchase.form = JSON.parse(JSON.stringify(row))
    },
    /** 查询商品SKU耗材列表 */
    getList() {
      this.loading = true
      listSkuConsumable(this.queryParams).then((response) => {
        this.skuConsumableList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        cesNo: undefined,
        cesName: undefined,
        specification: undefined,
        cesImg: '',
        cesPositionNo: undefined,
        cesType: undefined,
        num: undefined,
        price: undefined,
        priceUnit: undefined,
        purchaseLink1: undefined,
        purchaseLink2: undefined,
        purchaseLink3: undefined,
        purchaseRemark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined,
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()

      getCesNo().then((res) => {
        const { code, data, msg } = res
        if (code === 200) {
          this.form.cesNo = msg
          this.open = true
          this.title = this.$t('添加')
        }
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true
      this.reset()
      const id = row.id || this.ids
      getSkuConsumable(id).then((response) => {
        this.loading = false
        this.form = response.data
        this.open = true
        this.title = '修改商品SKU耗材'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          if (this.form.id != null) {
            updateSkuConsumable(this.form)
              .then((response) => {
                this.$modal.msgSuccess('修改成功')
                this.open = false
                this.getList()
              })
              .finally(() => {
                this.buttonLoading = false
              })
          } else {
            addSkuConsumable(this.form)
              .then((response) => {
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.getList()
              })
              .finally(() => {
                this.buttonLoading = false
              })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除商品SKU耗材编号为"' + ids + '"的数据项？')
        .then(() => {
          this.loading = true
          return delSkuConsumable(ids)
        })
        .then(() => {
          this.loading = false
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'distribution/skuConsumable/export',
        {
          ...this.queryParams,
        },
        `skuConsumable_${new Date().getTime()}.xlsx`,
      )
    },
  },
}
</script>

<style lang="scss" scoped>
//隐藏图片上传框的css
::v-deep.disabled {
  .el-upload--picture-card {
    display: none;
  }
}
</style>
